package Example;

import java.util.Scanner;

//题目：有一分数序列：2/1，3/2，5/3，8/5，13/8，21/13... 求出这个数列的前20项之和。
//注意分析分子分母的规律(分子的值是前一项的分母...后一项的分子分母是前两项的和)
public class Demo18 {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("请输入一个数计算前多少项之和：");
        int n = scan.nextInt();
        int[] molecular = new int[n];
        int[] denominator = new int[n];
        double sum = 0;
        if (n == 1) {
            molecular[0] = 1;
            denominator[0] = 2;
            sum = denominator[0] / molecular[0];
            System.out.println("前" + n + "项的结果为" + sum);
            return;
        }

        molecular[0] = 1;//分母
        denominator[0] = 2;//分子
        molecular[1] = 2;
        denominator[1] = 3;
        sum = ((double) denominator[0] / (double) molecular[0]) + ((double) denominator[1] / (double) molecular[1]);
        for (int i = 2; i < n; i++) {
            molecular[i] = denominator[i-1];//下一项的分母
            denominator[i] = denominator[i - 1] + molecular[i-1];//下一项的分子
            sum = sum + ((double) denominator[i] / (double) molecular[i]);
        }
        System.out.println("前" + n + "项之和为\n" + sum);
    }
}
